package com.easyj.admin.sys.controller;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.easyj.base.common.ajax.Result;
import com.easyj.base.common.imp.ImpUtils;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.ValidateException;
import com.easyj.base.security.service.SecurityUtil;
import com.easyj.base.util.DateTimeUtil;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.easyj.admin.db.model.ImpResult;
import com.easyj.admin.db.model.Position;
import com.easyj.admin.sys.service.PositionService;
	/**
	* 岗位
	*
	 */
	@RestController
	@RequestMapping(value = "/sys/position")
	public class PositionController extends BaseController{

		@Autowired
		private  PositionService positionService;

		/**
		 * get
		 * @param id
		 * @return
		 */
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	        Position entity = positionService.findById(id);
	        return Result.Success(entity);
	    }
		
		/**
		* 新增
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('position','position:all')")
		@PostMapping
		public Result add(@RequestBody @Validated Position entity,BindingResult validResult) throws EasyjException {
			
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 			
			positionService.insertEntity(entity);
			return Result.Success();
			
		}
		
		/**
		* 修改
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('position','position:all')")
		@PutMapping
		public Result update(@RequestBody @Validated Position entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			}  			
			positionService.updateEntity(entity);
			return Result.Success();
			
		}
		/**
		* 查询
		* @param filter
		* @return
		 */
		@PostMapping(value = "findList")
		public Result findList(@RequestBody  Position filter) {
			List<Position>  list =positionService.findList(filter);
			return Result.Success(list);
		}
		
        /**
 		 *删除
         * @throws EasyjException 
 		*/
 		@PreAuthorize("hasPermission('position','position:all')")
 		@DeleteMapping("/{id}")
 		public Result delete(@PathVariable("id") Long id) throws EasyjException{
			positionService.deleteById(id);
			return Result.Success();
 			
 		}
 		
 		@RequestMapping(value = "findUsersByPositionId", method = {RequestMethod.POST,RequestMethod.GET})
 		public Result findUsersByPositionId(@RequestParam(value = "id") Long id){					
 	    	return Result.Success(positionService.findUsersByPositionId(id));
 		}
 		

		/**
		  *  下载导入模板
		 * @param response
		 */
 		@PreAuthorize("hasPermission('position','position:all')")
		@RequestMapping(value = "exportTpl", method = RequestMethod.GET)
		public void exportTpl( HttpServletResponse response){
			try {
				//生成 excel
				SXSSFWorkbook workbook=ImpUtils.getImpTemplateExcel("position.xml","");
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="岗位导入模板"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			}catch (Exception ex) {
				log.error("PositionController.exportTpl", ex);
			} 
		}		
		
		/**
		 * 导入
		 * 配合element upload 控件
	     * 直接  throw error
		 * @param file
		 * @return
		 * @throws Exception
		 */
 		@PreAuthorize("hasPermission('position','position:all')")
		@RequestMapping(value = "importExcel", method = RequestMethod.POST)
		public Result importExcel(@RequestParam MultipartFile file) throws Exception{
			ImpResult rtn=positionService.importExcel(file, SecurityUtil.getOperatorId());
			return Result.Success(rtn);
		}

}

